package com.lfnyxy.web.org;

import com.lfnyxy.common.LogTool;
import com.lfnyxy.common.StringTool;
import com.lfnyxy.common.dto.ApiResult;
import com.lfnyxy.common.dto.CodeMessage;
import com.lfnyxy.common.dto.PagedDataTable;
import com.lfnyxy.eenum.SysUserType;
import com.lfnyxy.entity.org.SysUserEntity;
import com.lfnyxy.query.org.SysUserQuery;
import com.lfnyxy.service.org.EmpowerService;
import com.lfnyxy.service.org.SysUserService;
import com.lfnyxy.util.MD5Service;
import com.lfnyxy.vo.LoginUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by.
 */
@Controller
@RequestMapping("/sysuser")
@ResponseBody
public class SysUserController {
    @Autowired
    SysUserService sysUserService;

    @Autowired
    EmpowerService empowerService;

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult<Integer> CreateSysUser(@RequestBody SysUserEntity item) {
        if(item != null){
            item.setTypeId(SysUserType.SYS_USER.getCode());
            return saveUser(item);
        }
        return ApiResult.error(CodeMessage.QUERY_PARAM_ERROR);
    }

    @RequestMapping(value = "/csave", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult<Integer> CreateClientUser(@RequestBody SysUserEntity item) {
        if(item != null){
            item.setTypeId(SysUserType.CLIENT_USER.getCode());
            return saveUser(item);
        }
        return ApiResult.error(CodeMessage.QUERY_PARAM_ERROR);
    }

    private ApiResult<Integer> saveUser(SysUserEntity item){
        int result = 0;
        if (item != null) {
            try {
                if (item.getId() > 0) {
                    result = sysUserService.UpdateItem(item);
                } else {
                    //较验帐号是否存在。
                    SysUserEntity entity = sysUserService.QueryItemByAccount(item.getAccount());
                    if(entity != null){
                        return ApiResult.error(CodeMessage.USER_DUPLICATION);
                    }else {
                        sysUserService.CreateItem(item);
                        result = item.getId();
                    }
                }
            } catch (Exception ex) {
                LogTool.WriteError(this.getClass().toString() + "001-ex", ex.getMessage());
                return ApiResult.error(CodeMessage.SAVE_FAILED);
            }
        }
        return ApiResult.success(result);
    }


    @RequestMapping(value = {"/plist"}, method = {RequestMethod.GET})
    @ResponseBody
    public PagedDataTable QuerySysUserPageList(@RequestParam(value = "start", required = false) int start, @RequestParam(value = "length", required = false) int length, @RequestParam(value = "matchString", required = false) String matchString) {
        List<SysUserEntity> result = null;
        SysUserQuery query = new SysUserQuery();
        query.setStart(start);
        query.setLength(length);
        query.setUserTypeId(SysUserType.SYS_USER.getCode());
        if(StringTool.isNotEmpty(matchString)){
            query.setMatchString(matchString);
        }
        try {
            result = sysUserService.QueryPageList(query);
        } catch (Exception ex) {
            LogTool.WriteError(this.getClass().toString() + "002", ex.getMessage());
        }
        return new PagedDataTable<SysUserEntity>(query.getTotal(), result);
    }

    @RequestMapping(value = {"/pclist"}, method = {RequestMethod.GET})
    @ResponseBody
    public PagedDataTable QueryClientUserPageList(@RequestParam(value = "start", required = false) int start, @RequestParam(value = "length", required = false) int length, @RequestParam(value = "matchString", required = false) String matchString) {
        List<SysUserEntity> result = null;
        SysUserQuery query = new SysUserQuery();
        query.setStart(start);
        query.setLength(length);
        query.setUserTypeId(SysUserType.CLIENT_USER.getCode());
        if(StringTool.isNotEmpty(matchString)){
            query.setMatchString(matchString);
        }
        try {
            result = sysUserService.QueryPageList(query);
        } catch (Exception ex) {
            LogTool.WriteError(this.getClass().toString() + "002", ex.getMessage());
        }
        return new PagedDataTable<SysUserEntity>(query.getTotal(), result);
    }

    @RequestMapping(value = {"/item"}, method = {RequestMethod.POST})
    @ResponseBody
    public ApiResult<SysUserEntity> QueryItem(@RequestBody SysUserQuery query) {
        if (query != null && query.getId() > 0) {
            try {
                SysUserEntity result = sysUserService.QueryItem(query.getId());
                return ApiResult.success(result);
            } catch (Exception ex) {
                LogTool.WriteError(this.getClass().toString() + "003", ex.getMessage());
            }
        }
        return ApiResult.error(CodeMessage.GET_ITEM_FAILED);
    }

    @RequestMapping(value = {"/ditem"}, method = {RequestMethod.POST})
    @ResponseBody
    public ApiResult<Integer> DeleteItem(@RequestBody SysUserQuery query) {
        try {
            if (query != null && query.getId() > 0) {
                int cnt = sysUserService.DeleteItem(query.getId());
                return ApiResult.success(cnt);
            }
        } catch (Exception ex) {
            LogTool.WriteError(this.getClass().toString() + "004", ex.getMessage());
        }
        return ApiResult.error(CodeMessage.DELETE_ITEM_FAILED);
    }

    @RequestMapping(value = {"/all"}, method = {RequestMethod.POST})
    @ResponseBody
    public ApiResult<List<SysUserEntity>> QueryAll() {
        try {
            return ApiResult.success(sysUserService.QueryAll());
        } catch (Exception ex) {
            LogTool.WriteError(this.getClass().toString() + "005", ex.getMessage());
            return ApiResult.error(CodeMessage.QUERY_LIST_FAILED);
        }
    }

    @RequestMapping(value = {"login"}, method = {RequestMethod.POST})
    @ResponseBody
    public ApiResult<SysUserEntity> userLogin(@RequestBody LoginUserVo userVo, HttpSession session) {

        if(userVo==null || StringTool.isEmpty(userVo.getAccount()) || StringTool.isEmpty(userVo.getPassword())) {
            return ApiResult.error(CodeMessage.LOGIN_ERROR);
        }

        String uID = userVo.getAccount();
        String pwd = userVo.getPassword();
        String vCode = userVo.getCode();

//        String genCode = (String) session.getAttribute("CAPTCHA");
//        if(StringUtils.isEmpty(genCode) || !genCode.equalsIgnoreCase(vCode.trim())){
//            return ApiResult.error(CodeMessage.LOGIN_CODE_ERROR);
//        }
        if(!StringUtils.isEmpty(uID)){
            SysUserEntity user = sysUserService.QueryItemByAccount(uID);
            if(user != null){
                String mPass = MD5Service.formPassToDbPass(pwd , user.getSalt());
                if(mPass.equals(user.getPassword())){
                    return ApiResult.success(user);
                }else{
                    return ApiResult.error(CodeMessage.LOGIN_PASSWORD_ERROR);
                }
            }
        }
        return ApiResult.error(CodeMessage.LOGIN_ERROR);
    }
}